package idv.arthur.work;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class UpdateMapping
 */
//@WebServlet(description = "修改uID與tcID間的對應", urlPatterns = { "/UpdateMapping" })
public class UpdateMapping extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpdateMapping() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String strRes = "";	//最後執行的結果回傳
		Widgets wid = new Widgets();

		String tcID = request.getParameter("q_tcID"); // 測試案例ID
		String uID = request.getParameter("presentUID"); // 測試案例ID
		String creator = request.getParameter("loginUser"); // 創建者
		
		Connection conn = wid.getConn(true);
		PreparedStatement ps = null;
		ResultSet rs = null;

		try {
			
			// 更新前先將所有的該測試案例ID的記錄都將其active設為0, 等下再將使用者點選的設為1
			String strUpdateMapping_1 = "UPDATE tms_tcidmapping SET active=false WHERE tcID=?";
			ps = conn.prepareStatement(strUpdateMapping_1);
			ps.setString(1, tcID);
			ps.executeUpdate();
			
			String strUpdateMapping_2 = "UPDATE tms_tcidmapping SET active=true,LastUpdateID=?,LastUpdatedTime=? WHERE tcID=? AND uID=?";
			ps = conn.prepareStatement(strUpdateMapping_2);
			ps.setString(1, creator);
			ps.setTimestamp(2, wid.currentTimeStamp());
			ps.setString(3, wid.changeCode(tcID));
			ps.setString(4, uID);
			ps.executeUpdate();
			
			wid.keepLogTC(tcID, Long.valueOf(uID), creator, 3, conn, ps);
		} catch (SQLException e) {
			strRes = e.toString();
			wid.keepErrorMes(conn, ps, e, "", true);
		} finally {
			try {
				if (rs!= null) {rs.close();}
				if (ps!= null) {ps.close();}
				if (conn!= null) {conn.close();}
			} catch (SQLException e) {
				strRes = e.toString(); 
				System.out.println(strRes);
			}
		}
		
		strRes ="更新動作結束";
		response.setContentType("application/text");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(strRes);
	}
}
